package ducct.footprint.db;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;

public class DatabaseBackgroundWorker extends Thread {
	public static final String TAG = "DatabaseThreadWorker";
	
	private static List<DbTask> queue = new ArrayList<DbTask>();
	
	private static DatabaseBackgroundWorker worker = null;
	
	private volatile boolean running = true;
	
	public static void startWaitingForDbTask() {
		worker = new DatabaseBackgroundWorker();
	}
	
	private DatabaseBackgroundWorker() {
		worker = this;
		start();
	}
	
	public static void queueDbTask(DbTask dbTask) {
		if (worker != null) {
			synchronized (worker) {
				if (dbTask.isImportant()) {
					queue.add(0, dbTask);
				} else {
					queue.add(dbTask);
				}
				worker.notify();
			}
		}
	}

	@Override
	public void run() {
		Log.w(TAG, "Start DatabaseBackgroundWorker");
		
		while (running) {
			synchronized (this) {
				if (queue.isEmpty()) {
					Log.w(TAG, "Waiting for new db requests...");
					try {
						wait();
					} catch (InterruptedException e) {}
				} 
			}
			
			if (!running) {
				break;
			}
			
			Log.w(TAG, "Execute a db task");
			DbTask dbTask = queue.remove(0);
			dbTask.loadData();
		}
		
		Log.w(TAG, "Stop DatabaseBackgroundWorker");
	}
	
	public static void stopThread() {
		if (worker != null) {
			synchronized (worker) {
				queue.clear();
				worker.running = false;
				worker.notify();
				worker.interrupt();
			}
		}
	}
}
